<?php

namespace app\admin\controller\microend;

use app\common\controller\Backend;
use think\Db;

/**
 * 提现记录管理
 *
 * @icon fa fa-circle-o
 */
class UserCash extends Backend
{

    /**
     * Cash模型对象
     * @var \app\common\model\user\Cash
     */
    protected $model = null;

    protected $user_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\user\Cash;
        $this->user_model = new \app\common\model\User;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $_where["h.status"] = 1;

            $join[] = ["sd_user r","r.uid = h.uid","left"];

            $field = "r.username,r.tao_bao_no,r.mobile,r.cashed,r.uid,r.balance";

            $field .= ",h.balance,h.cash,h.created_time,h.status,h.cash_id";



            $total = $this->model
                ->alias("h")
                ->join($join)
                ->where($where)
                //->where($_where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->alias("h")
                ->join($join)
                ->field($field)
//                ->with("user")
//                ->field("*,cash_id as id")
                ->where($where)
                //->where($_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as &$value){

                $value["h.created_time"] = $value["created_time"];
                $value["h.status"] = $value["status"];
                $value["h.balance"] = $value["balance"];

            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 改变状态
     *
     *
     */
    public function update_status(){

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params)
            {
                $user_this = Db::name("user_cash")->where(["cash_id"=>$params["row"]["cash_id"]])->find();
                //halt($user_this);
                if($user_this["status"]==$params["type"]){
                    if($user_this["status"]==2){
                        renderJson("已提现",0);
                    }else{
                        renderJson("已驳回",0);
                    }
                }
                Db::startTrans();
                try{

                    $op = $this->model->save(["status"=>$params["type"]],["cash_id"=>$params["row"]["cash_id"]]);

                    $user_info = Db::name("user")->where(["uid" => $params["row"]["uid"]])->find();

                    if($op){
                        if($params["type"]==2) {
                            //echo $params["row"]["uid"];exit;
                            Db::name("user")->where(["uid" => $params["row"]["uid"]])->setInc("cashed", floatval($user_this["cash"]));
                            //echo Db::name("user")->getLastSql();exit;
//                            $fine_info = [
//                                "on_time"=>time(),
//                                "fina_type"=>"cash",
//                                "obj_type"=>"withdraw",
//                                "obj_id"=>$user_this["cash_id"],
//                                "uid"=>$user_info["uid"],
//                                "username"=>$user_info["username"],
//                                "fina_cash"=>$user_this["cash"],
//                                "fina_channel"=>1,
//                                "balance"=>0,
//                                "source"=>"system",
//                                "desc"=>'提现申请失败,系统支付成功',
//                                "remark"=>'提现申请失败,系统支付成功'
//                            ];
//
//
//
//                            Db::name("finance")->insert($fine_info);

                            $balance_msg = Db::name("user")->where("uid", $user_this["uid"])->value("balance");

                            $openid = Db::name("wx_users")->where("uid", $user_this["uid"])->value("openid");

                            $time_msg = date("Y-m-d H:i:s",$user_this["created_time"]);

                            $time_do = date("Y-m-d H:i:s",time());
                            $msg = [
                                "condition" => 17,
                                "touser" => $openid,
                                "content" => [$time_msg, $time_do, floatval($user_this["cash"]),$balance_msg]
                            ];
                            $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                            $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                        }
                        if($params["type"]==3){
                            Db::name("user")->where(["uid" => $params["row"]["uid"]])->setInc("balance", floatval($user_this["cash"]));
                            //Db::name("user")->where(["uid" => $params["row"]["uid"]])->setInc("",floatval($user_this["cash"]));
                            //Db::name("user_cash")->where(["cash_id"=>$params["row"]["cash_id"]])->delete();
                            $fine_info = [
                                "on_time"=>time(),
                                "fina_type"=>"cash",
                                "obj_type"=>"withdraw_fail",
                                "obj_id"=>$user_this["cash_id"],
                                "uid"=>$user_info["uid"],
                                "username"=>$user_info["username"],
                                "fina_cash"=>$user_this["cash"],
                                "fina_channel"=>1,
                                "balance"=>floatval($user_info["balance"])+floatval($user_this["cash"]),
                                "source"=>"paike",
                                "desc"=>'提现申请成功,系统支付失败',
                                "remark"=>'提现申请成功,系统支付失败'
                            ];
                            Db::name("finance")->insert($fine_info);

                            $openid = Db::name("wx_users")->where("uid", $user_this["uid"])->value("openid");

                            $time_msg = date("Y-m-d H:i:s",$user_this["created_time"]);

                            $msg = [
                                "condition" => 18,
                                "touser" => $openid,
                                "content" => [floatval($user_this["cash"]), $time_msg, "管理员驳回该信息"]
                            ];
                            $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                            $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
                        }
                        Db::commit();
                        renderJson("成功", 1);
                    }else{
                        renderJson("失败", 0);
                    }

                }catch (\Exception $e){
                    echo $e->getMessage();exit;
                    renderJson("失败", 0);
                }

            }
        }
    }



    /**
     *
     * 批量驳回
     *
     */
    public function mult_no()
    {
        $pass = input("post.");
        $ids = [];
        if($pass["ids"]) {
            $msg_cash = [];
            $uid_arr = [];
            $count = 0;
            foreach ($pass["ids"] as $k => $v) {
                if ($v["status"] == 1) {
                    $ids[] = $v["cash_id"];
                    Db::name("user")->where(["uid" => $v["uid"]])->setInc("balance", floatval($v["cash"]));
                    $uid_arr[] = $v["uid"];
                    $msg_cash[$count]["cash"] =floatval($v["cash"]);
                    $msg_cash[$count]["uid"] =$v["uid"];
                    $msg_cash[$count]["created_time"] =$v["created_time"];
                    $fine_info = [
                        "on_time" => time(),
                        "fina_type" => "cash",
                        "obj_type" => "withdraw_fail",
                        "obj_id" => $v["cash_id"],
                        "uid" => $v["uid"],
                        "username" => $v["username"],
                        "fina_cash" => $v["cash"],
                        "fina_channel" => 1,
                        "balance" => floatval($v["balance"])+floatval($v["cash"]),
                        "source" => "paike",
                        "desc" => '提现申请失败,系统支付失败',
                        "remark" => '提现申请失败,系统支付失败'
                    ];
                    Db::name("finance")->insert($fine_info);
                    $count++;
                }
                //echo $count;exit;
            }
            Db::name("user_cash")->where("cash_id", "in", $ids)->update(["status" => 3]);
            $openid = Db::name("wx_users")->where("uid","in",$uid_arr)->field("openid,uid")->select();
            $openid_arr = [];
            foreach ($openid as &$v){
                $openid_arr[$v["uid"]] = $v["openid"];
            }
            //halt($openid_arr);
            foreach ($msg_cash as &$value) {
                $time_msg = date("Y-m-d H:i:s", $value["created_time"]);
                $msg = [
                    "condition" => 18,
                    "touser" => $openid_arr[$value["uid"]],
                    "content" => [floatval($value["cash"]), $time_msg, "管理员驳回该信息"]
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
            }
            if($count==0){
                renderJson("没有合适的选项", 0);
            }
            renderJson("驳回成功", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }

    }


    /**
     *
     * 批量通过
     */
    public function mult_pass()
    {
        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            $up = [];
            $msg_cash = [];
            $uid_arr = [];
            $count = 0;
            //halt($pass["ids"]);
            foreach ($pass["ids"] as $k => $v) {
                if($v["status"]==1) {
                    $uid_arr[] = $v["uid"];
                    $msg_cash[$count]["cash"] =floatval($v["cash"]);
                    $msg_cash[$count]["uid"] =$v["uid"];
                    $msg_cash[$count]["created_time"] =$v["created_time"];
                     $ids[] = $v["cash_id"];
//                    $fine_info = [
//                        "on_time" => time(),
//                        "fina_type" => "cash",
//                        "obj_type" => "cash",
//                        "obj_id" => $v["cash_id"],
//                        "uid" => $v["uid"],
//                        "username" => $v["username"],
//                        "fina_cash" => $v["cash"],
//                        "fina_channel" => 1,
//                        "balance" => 0,
//                        "source" => "system",
//                        "desc" => '提现申请成功,系统支付成功',
//                        "remark" => '提现申请成功,系统支付成功'
//                    ];
//                    Db::name("finance")->insert($fine_info);
                    Db::name("user")->where(["uid" => $v["uid"]])->setInc("cashed", floatval($v["cash"]));
                    $count++;
                }
            }
            $openid = Db::name("wx_users")->where("uid","in",$uid_arr)->field("openid,uid")->select();
            $openid_arr = [];
            foreach ($openid as &$v){
                $openid_arr[$v["uid"]] = $v["openid"];
            }
            $balance_msg = Db::name("user")->where("uid", 'in',$uid_arr)->field("balance,uid")->select();
            $balance_msg_arr = [];
            foreach ($balance_msg as &$v){
                $balance_msg_arr[$v["uid"]] = $v["balance"];
            }
            foreach ($msg_cash as &$value) {
                $time_msg = date("Y-m-d H:i:s", $value["created_time"]);
                $time_do = date("Y-m-d H:i:s", time());
                $msg = [
                    "condition" => 17,
                    "touser" => $openid_arr[$value["uid"]],
                    "content" => [$time_msg, $time_do, floatval($value["cash"]), $balance_msg_arr[$value["uid"]]]
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
            }
            Db::name("user_cash")->where("cash_id", "in", $ids)->update(["status" => 2]);
            if($count==0){
                renderJson("没有合适的选项", 0);
            }
            renderJson("通过成功", 1);
        }else{
            renderJson("请勾选你的选项", 0);
        }

    }


    /**
     * 测试
     */
    public function test(){

        echo numTrmb(109.1);
    }


    /**
     * 汇款导出
     */
    public function export_act(){

        if ($this->request->isGet()) {
            $params = $this->request->get();
            if ($params)
            {

                //halt($params);
                if($params["ids"]){//批量发送
                    $params["ids"] = (string)$params["ids"];
                    $ids = explode(",",$params["ids"]);
                    //$join[] = ["sd_shop_order r","r.order_id = d.order_id","left"];
                    $record_money_list = Db::name("user_cash")->where("cash_id","in",$ids)->select();
                    $data = [];
                    //获取所有的金额
                    foreach ($record_money_list as $key=>$value){
                        $data[$key]["username"] = $value["username"];//用户名
                        $data[$key]["bank_no"] = (string)$value["bank_code"]." ";//卡号
                        $data[$key]["bank_name"] = $value["bank_name"];//名称
                        $data[$key]["cash"] = $value["cash"];//现金
                        $data[$key]["on_time"] = date("Y-m-d H:i:s",$value["created_time"]);
                    }
                    /**
                     * 数据导出
                     * @param array $title   标题行名称
                     * @param array $data   导出数据
                     * @param string $fileName 文件名
                     * @param string $savePath 保存路径
                     * @param $type   是否下载  false--保存   true--下载
                     * @return string   返回文件全路径
                     * @throws PHPExcel_Exception
                     * @throws PHPExcel_Reader_Exception
                     */
                    $this->export(["用户名","卡号","名称","现金","提现时间"],$data,'提现','./',true);

                }


            }
        }

    }

}
